package com.tbvtc.agriculturalcreditchainserver2025.controller.admin;
import com.google.common.collect.Lists;
import com.tbvtc.agriculturalcreditchainserver2025.enumeration.MessageType;
import com.tbvtc.agriculturalcreditchainserver2025.enumeration.ChatType;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tbvtc.agriculturalcreditchainserver2025.dto.Cart.GroupData;
import com.tbvtc.agriculturalcreditchainserver2025.dto.Cart.UserOrderLimitDot;
import com.tbvtc.agriculturalcreditchainserver2025.dto.ReportSumByTypeDto;
import com.tbvtc.agriculturalcreditchainserver2025.entity.Crop;
import com.tbvtc.agriculturalcreditchainserver2025.entity.CropFertilizerCheck;
import com.tbvtc.agriculturalcreditchainserver2025.entity.Test;
import com.tbvtc.agriculturalcreditchainserver2025.entity.websocket.WebSocketMessage;
import com.tbvtc.agriculturalcreditchainserver2025.service.*;
import com.tbvtc.agriculturalcreditchainserver2025.service.impl.TestServiceImpl;
import com.tbvtc.agriculturalcreditchainserver2025.utils.CustomMultipartFile;
import com.tbvtc.agriculturalcreditchainserver2025.utils.RUtils;
import com.tbvtc.agriculturalcreditchainserver2025.utils.Result;
import com.tbvtc.agriculturalcreditchainserver2025.vo.ConsumerVo.*;

import com.tbvtc.agriculturalcreditchainserver2025.ws.WebSocketServer;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;

import org.fisco.bcos.sdk.transaction.model.dto.TransactionResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.Base64;
import java.util.List;

@CrossOrigin
@RestController
@Tag(name = "消费者")
@Slf4j
@RequestMapping("/consumer")
public class ConsumerControlleer {
    @Autowired
    private ConsumerService consumerService;
    @Resource
    private IOrdersService ordersService;
    @Autowired
    private TestServiceImpl testServiceImpl;
    @Resource
    private ITestService testService;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private ICropService cropService;
    @Resource
    private ICropFertilizerCheckService cropFertilizerCheckService;
    @Resource
    private IChatMessageService chatMessageService;

    @Operation(summary = "获取溯源信息")
    @PostMapping("/getTraceInfo")
    @Parameter(name = "foodName", description = "农产品名称")
    public Result getTraceInfo(String foodName) throws Exception {
        List info = consumerService.getTraceInfo(foodName);
        TraceInfoVo traceInfoVo = new TraceInfoVo(info);
        return RUtils.success(traceInfoVo);
    }

    // 获取特定农作物的所有报告
    @Operation(summary = "获取特定农作物的所有报告")
    @PostMapping("/getAllReport")
    @Parameter(name = "foodName", description = "农产品名称")
    public Result getAllReport(String foodName) throws Exception {
        List info = consumerService.getAllReport(foodName);
        return RUtils.success(info);
    }

    // 获取特定农作物的所有报告摘要
    @Operation(summary = "获取特定农作物的所有报告摘要")
    @PostMapping("/getAllReportSummary")
    @Parameter(name = "foodName", description = "农产品名称")
    public Result getAllReportSummary(String foodName) throws Exception {
        List info = consumerService.getAllReportSummary(foodName);
        AllReportSummaryVo info1 = new AllReportSummaryVo(info);
        return RUtils.success(info1);
    }

    // 获取特定类型的报告摘要
    @Operation(summary = "获取特定类型的报告摘要")
    @PostMapping("/getReportSummaryByType")
    public Result getReportSummaryByType(@RequestBody ReportSumByTypeDto reportSumByTypeDto) throws Exception {
        List info = consumerService.getReportSummaryByType(reportSumByTypeDto);
        ReportSumByTypeVo reportSum = new ReportSumByTypeVo(info);
        return RUtils.success(reportSum);
    }

    /**
     * 下单购买
     * @param placeOrderVo
     * @return
     * @throws Exception
     */
    @Operation(summary = "下单购买")
    @PostMapping("/buy")
    public Result buy(@RequestBody PlaceOrderVo placeOrderVo) throws Exception {

        return RUtils.success( testService.buy(placeOrderVo));
    }

    /**
     *  支付成功
     * @param orderId
     * @return
     */
    @Operation(summary = "支付成功")
    @PostMapping("/paySuccess")
    @Parameter(name = "orderId", description = "订单编号")
    public Result paySuccess(String orderId) {
        if (orderId == null) {
            return RUtils.Err(0, "订单编号不能为空");
        }
        Test order = testService.getOne(new LambdaQueryWrapper<Test>()
                .eq(Test::getOrderId, orderId)
        );
        if (order.getState()!=0){
           return RUtils.Err(0, "订单已支付");
        }
        order.setState(1);
        testService.updateById(order);
        //支付完成后删除缓存
        stringRedisTemplate.delete("order:" + orderId);
        return RUtils.success();
    }

    /**
     * 支付失败
     * @param orderId
     * @return
     */
    @Operation(summary = "根据orderId支付未支付订单")
    @PostMapping("/payFailed")
    @Parameter(name = "orderId", description = "订单编号")
    public Result payFailed(String orderId) {
        if (orderId == null) {
            return RUtils.Err(0, "订单编号不能为空");
        }
        Test order = testService.getOne(new LambdaQueryWrapper<Test>()
                .eq(Test::getOrderId, orderId)
        );
        if (order.getState()!=0){
            return RUtils.Err(0, "此状态不允许修改");
        }
        Boolean flag = stringRedisTemplate.hasKey("order:" + orderId);
        if (!flag) {
            order.setState(-1);
            testService.updateById(order);
            return RUtils.Err(0, "订单已超时");
        }
        //如果未过15分钟则支付
        return paySuccess(orderId);
    }

    /**
     * 收货
     * @param orderId
     * @return
     */
    @Operation(summary = "收货")
    @PostMapping("/receive")
    @Parameter(name = "orderId", description = "订单编号")
    public Result receive(String orderId) {
        if (orderId == null) {
            return RUtils.Err(0, "订单编号不能为空");
        }
        Test order = testService.getOne(new LambdaQueryWrapper<Test>()
                .eq(Test::getOrderId, orderId)
        );
        if (order.getState()!=2){
            return RUtils.Err(0, "此状态不允许修改");
        }
        order.setState(3);
        testService.updateById(order);
        return RUtils.success();
    }


//    @Operation(summary = "确认发货")
//    @PostMapping("/confirmDelivery")
//    @Parameters({
//            @Parameter(name = "orderId", description = "订单编号"),
//            @Parameter(name = "logisticsInfo", description = "物流信息")
//    })
//    public Result confirmDelivery(String orderId, String logisticsInfo) throws Exception {
//        TransactionResponse response = consumerService.confirmDelivery(orderId, logisticsInfo);
//        return RUtils.success(response);
//    }

    @Operation(summary = "获取订单发货状态")
    @PostMapping("/getOrderDeliveredStatus")
    public Result getOrderDeliveredStatus(@RequestBody UserOrderLimitDot userOrderLimitDot) throws Exception {
        return RUtils.success( testService.findOrderByConsumerId(userOrderLimitDot));
    }

    @Operation(summary = "获取订单发货数量")
    @PostMapping("/getDeliveryCount")
    public Result getDeliveryCount() throws Exception {
        List count = consumerService.getDeliveryCount();
        return RUtils.success(count);
    }
    /**
     *  消费者物流
     * @param userOrderLimitDot
     * @return
     */
    @Operation(summary = "消费者物流")
    @PostMapping("/findOrderById")
    public Result findOrderById(@RequestBody UserOrderLimitDot userOrderLimitDot) {
//        ResultPage<GroupData> orderById = cartService.findOrderById(userOrderLimitDot);5
        List<GroupData> list=  testService.findOrderByConsumerId(userOrderLimitDot);
        return RUtils.success(list);
    }


    /**
     * 查询全部商品
     * @return
     */
    @Operation(summary = "查询全部商品")
    @PostMapping("/findAllGoods")
    public Result findAllCrop() {
        List<Crop> list = cropService.list(new LambdaQueryWrapper<Crop>()
                .eq(Crop::getIsSale, 1)
        );
        return RUtils.success(list);
    }

    @Operation(summary = "取消订单")
    @PutMapping("/cancelOrder")
    public Result cancelOrder(String orderId) throws Exception {

        return RUtils.success();
    }

    @Operation(summary = "获取检测报告")
    @GetMapping("/getDetectionReport")
    public Result getDetectionReport(String cropId) throws Exception {

        return  cropFertilizerCheckService.getDetectionReport(cropId);
    }

    @Operation(summary = "test")
    @PostMapping("/test")
    public Result test( @RequestPart("file") MultipartFile file) throws Exception {
        WebSocketMessage webSocketServer = new WebSocketMessage();
        webSocketServer.setChatType(ChatType.SINGLE_SEND);
        webSocketServer.setMessageType(MessageType.AUDIO);
        webSocketServer.setContent(List.of("你还高"));
        webSocketServer.setSenderId("9");
        webSocketServer.setReceiverId(List.of("1"));
        webSocketServer.setGroupId("");
        webSocketServer.setMetadata(Lists.newArrayList());
        webSocketServer.setFilePath(Lists.newArrayList());
        String base64 = Base64.getEncoder().encodeToString(file.getBytes());
        chatMessageService.singleSend(webSocketServer);
        return  RUtils.success();
    }

}
